package http.ach;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

// 用于解析请求
public class HttpRequest {
    // 请求方法
    private String method;
    // 请求路径
    private String url;
    // Http 版本
    private String version;
    // 请求头
    private Map<String,String> headers = new HashMap<>();
    // 请求参数
    private Map<String,String> parameters = new HashMap<>();
    // 统一编码
    private static final String CHARSET = "UTF-8";

    // 利用工厂方法创建实体类 : 工厂模式
    public static HttpRequest build(InputStream inputStream) throws IOException {
        HttpRequest request = new HttpRequest();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,CHARSET));

        // 处理亲求行
        String[] requestLineArray = bufferedReader.readLine().split(" ");
        request.method = requestLineArray[0];
        request.url = requestLineArray[1];
        request.version = requestLineArray[2];

        // 处理请求头
        String requestHeader;
        while((requestHeader = bufferedReader.readLine()) != null && requestHeader.length() != 0){
            String[] headArray = requestHeader.split(": ");
            request.headers.put(headArray[0].trim(),headArray[1].trim());
        }
        // 处理 body 暂时不涉及
        return request;
    }
    // 请求解析只能查看不能 改 所以只设置 getter 方法


    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getVersion() {
        return version;
    }

    public String getHeaders(String key) {
        return headers.get(key);
    }

    public String getParameters(String key) {
        return parameters.get(key);
    }

    public static String getCHARSET() {
        return CHARSET;
    }

    @Override
    public String toString() {
        return "HttpRequest{" +
                "method='" + method + '\'' +
                ", url='" + url + '\'' +
                ", version='" + version + '\'' +
                ", headers=" + headers +
                ", parameters=" + parameters +
                '}';
    }
}
